package com.ebookstore.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ebookstore.dto.UserInfo;
import com.ebookstore.exception.EBookStoreException;
import com.ebookstore.struts.form.CartForm;
import com.ebookstore.struts.form.OrderForm;

public class OrderAction extends BaseAction {

	/**
	 * 新建订单
	 */
	public ActionForward newOrder(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		OrderForm orderForm = (OrderForm) form;
		//如果需要输入地址信息，并且地址为空
		System.out.println("OrderAction.newOrder() isRequired="+orderForm.isShippingAddressRequired()
				+"   address="+orderForm.getShipaddress());
		if (orderForm.isShippingAddressRequired()
				&& ("".equals(orderForm.getShipaddress())|| orderForm.getShipaddress()==null)) {
			return mapping.findForward("shipping");
		}
		//如果订单还未确认
		System.out.println("isConfirmed="+orderForm.isConfirmed());
		if (!orderForm.isConfirmed()) {
			return mapping.findForward("confirm");
		}
		return null;
	}
	
	/**
	 * 保存订单
	 */
	public ActionForward saveOrder(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws EBookStoreException {
		OrderForm orderForm = (OrderForm) form;//订单信息
		UserInfo user = (UserInfo) request.getSession().getAttribute("loginUser");//用户登录信息
		CartForm cartForm = (CartForm) request.getSession().getAttribute("cartForm");//购物车信息
		//如果未登录，则提示登录
		if (user == null ) {
			request.setAttribute("message", "您还未登录，请登录后下订单");
			return mapping.findForward("failure");
		}
		if (orderForm.getOrder() != null) {
			//保存订单
			getEBookStore().getOrderService().addOrder(orderForm.getOrder(),
					cartForm.getCart(), user);
			//清空缓存
			request.getSession().removeAttribute("orderForm");
			request.getSession().removeAttribute("cartForm");
			request.setAttribute("message", "您的订单已提交");
			return mapping.findForward("success");
		} else {
			request.setAttribute("message", "不能提交订单");
			return mapping.findForward("failure");
		}
	}
}
